<template>
  <div class="wallet">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-right">
            <h2>我的钱包</h2>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card class="wallet-card">
          <div class="balance-section">
            <div class="balance-title">账户余额</div>
            <div class="balance-amount">¥ {{ userBalance }}</div>
          </div>
          <div class="wallet-actions">
            <el-button type="primary" size="large" @click="showRechargeDialog">充值</el-button>
            <el-button type="warning" size="large">提现</el-button>
          </div>
          <div class="transaction-section">
            <div class="section-title">交易记录</div>
            <el-table :data="displayTransactions" style="width: 100%">
              <el-table-column prop="createdAt" label="日期" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="类型" width="120">
                <template #default="scope">
                  <span :class="getStatusClass(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="delta" label="金额" width="120">
                <template #default="scope">
                  <span :class="scope.row.delta >= 0 ? 'amount-positive' : 'amount-negative'">
                    {{ scope.row.delta >= 0 ? '+' : '' }}{{ scope.row.delta }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 充值对话框 -->
    <el-dialog v-model="rechargeDialogVisible" title="账户充值" width="400px">
      <el-form :model="rechargeForm" ref="rechargeFormRef" :rules="rechargeRules">
        <el-form-item label="充值金额" prop="amount">
          <el-input-number 
            v-model="rechargeForm.amount" 
            :min="0.01" 
            :precision="2" 
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge">确认充值</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getUserBalance, getUserTransactions } from '@/api/user'
import request from '@/utils/request'

const router = useRouter()
const userBalance = ref(0)
const transactions = ref([])
const rechargeDialogVisible = ref(false)
const rechargeFormRef = ref(null)

const rechargeForm = ref({
  amount: 100
})

const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '充值金额必须大于0', trigger: 'blur' }
  ]
}

// 显示充值对话框
const showRechargeDialog = () => {
  rechargeDialogVisible.value = true
}

// 处理充值
const handleRecharge = async () => {
  if (!rechargeFormRef.value) return
  
  try {
    await rechargeFormRef.value.validate()
    
    console.log('开始充值请求，金额:', rechargeForm.value.amount)
    
    const response = await request({
      url: '/api/alipay/recharge',
      method: 'post',
      params: { amount: rechargeForm.value.amount },
      timeout: 10000
    })

    console.log('充值接口响应:', response)

    // 获取支付表单HTML
    const formHtml = response.data.data
    
    // 检查响应中是否包含支付表单
    if (formHtml && typeof formHtml === 'string' && formHtml.includes('form')) {
      // 创建一个临时div来放置支付宝返回的表单
      const div = document.createElement('div')
      div.innerHTML = formHtml
      document.body.appendChild(div)
      
      try {
        // 提交表单
        const form = div.getElementsByTagName('form')[0]
        if (form) {
          console.log('找到支付表单，准备提交')
          // 使用新窗口打开支付页面
          form.target = '_blank'
          form.submit()
          
          // 监听支付完成消息
          window.addEventListener('message', handlePaymentMessage)
        } else {
          console.error('未找到支付表单')
          throw new Error('支付表单生成失败')
        }
      } catch (formError) {
        console.error('表单提交失败:', formError)
        throw new Error('支付表单提交失败，请重试')
      } finally {
        // 清理临时div
        document.body.removeChild(div)
      }
      
      rechargeDialogVisible.value = false
      ElMessage.success('正在跳转到支付页面，请在新窗口完成支付')
    } else {
      console.error('响应中没有找到支付表单:', formHtml)
      throw new Error('创建支付订单失败')
    }
  } catch (error) {
    console.error('充值失败，详细错误:', error)
    if (error.response) {
      console.error('错误响应数据:', error.response.data)
    }
    
    let errorMessage = '充值失败，请重试'
    if (error.code === 'ECONNABORTED') {
      errorMessage = '连接支付宝超时，请检查网络后重试'
    } else if (error.response && error.response.status === 504) {
      errorMessage = '支付网关超时，请稍后重试'
    }
    
    ElMessage.error(errorMessage)
  }
}

// 处理支付完成消息
const handlePaymentMessage = (event) => {
  // 验证消息来源
  if (event.origin !== window.location.origin) {
    return
  }

  const { type, success } = event.data
  if (type === 'payment_complete') {
    if (success) {
      ElMessage.success('支付成功，正在刷新数据...')
      // 刷新余额和交易记录
      loadUserBalance()
      loadTransactions()
    } else {
      ElMessage.error('支付失败，请查看交易记录或重试')
    }
    
    // 移除消息监听
    window.removeEventListener('message', handlePaymentMessage)
  }
}

// 在组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('message', handlePaymentMessage)
})

// 计算属性：只显示最新的5条记录
const displayTransactions = computed(() => {
  return transactions.value.slice(0, 5)
})

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取交易状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '转账'
    case 1:
      return '充值'
    case 3:
      return '支付'
    default:
      return '未知'
  }
}

// 获取交易状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 0:
      return 'status-income'
    case 1:
      return 'status-expense'
    case 3:
      return 'status-subsidy'
    default:
      return ''
  }
}

// 获取用户余额
const loadUserBalance = async () => {
  try {
    const res = await getUserBalance()
    userBalance.value = res
  } catch (error) {
    console.error('获取余额失败:', error)
    ElMessage.error('获取余额失败')
  }
}

// 获取交易记录
const loadTransactions = async () => {
  try {
    const res = await getUserTransactions()
    transactions.value = res
  } catch (error) {
    console.error('获取交易记录失败:', error)
    ElMessage.error('获取交易记录失败')
  }
}

// 处理支付回调错误
const handlePaymentError = () => {
  const error = router.currentRoute.value.query.error
  if (error) {
    switch (error) {
      case 'payment_verification_failed':
        ElMessage.error('支付验证失败，请联系客服')
        break
      case 'payment_processing_error':
        ElMessage.error('支付处理异常，请稍后查看交易记录')
        break
      default:
        ElMessage.error('支付过程中出现错误')
    }
    // 清除错误参数
    router.replace({ query: {} })
  }
}

onMounted(() => {
  loadUserBalance()
  loadTransactions()
  handlePaymentError()
  
  // 检查URL参数，判断是否是支付宝回调
  const urlParams = new URLSearchParams(window.location.search)
  const status = urlParams.get('status')
  const outTradeNo = urlParams.get('out_trade_no')
  const totalAmount = urlParams.get('total_amount')
  
  if (status === 'success' && outTradeNo && totalAmount) {
    ElMessage.success('支付完成，正在刷新余额...')
    loadUserBalance()
    loadTransactions()
    // 清除URL参数
    router.replace('/wallet')
  }
})
</script>

<style scoped>
.wallet {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.el-main {
  padding: 20px;
  max-width: 1200px;
  margin: 80px auto 0;
}

.wallet-card {
  padding: 20px;
}

.balance-section {
  text-align: center;
  padding: 40px 0;
  background: linear-gradient(135deg, #409EFF 0%, #36D1DC 100%);
  border-radius: 8px;
  color: white;
  margin-bottom: 30px;
}

.balance-title {
  font-size: 18px;
  margin-bottom: 10px;
}

.balance-amount {
  font-size: 48px;
  font-weight: bold;
}

.wallet-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 30px 0;
}

.transaction-section {
  margin-top: 30px;
  position: relative;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-positive {
  color: #67C23A;
  font-weight: bold;
}

.amount-negative {
  color: #F56C6C;
  font-weight: bold;
}

.status-income {
  color: #67C23A;
  font-weight: bold;
}

.status-expense {
  color: #F56C6C;
  font-weight: bold;
}

.status-subsidy {
  color: #E6A23C;
  font-weight: bold;
}
</style> 